import { CreepRole, RoleDatas } from "@/role/types/role"
import CreepController from "../controller"
import CreepNumberSettings from "../numberSettings"


class RoleReserver {

    static spawnRoomNames: string[] = ['E35S49', 'E39S52']
    static workRoomNames: string[][] = [['E34S48', 'E36S48'], ['E38S52']]
    static roomReserverIndexs: number[][][] = [[[0], [1]], [[0]]]
    /**
     *
     * @param creep
     * @returns
     */
    static loop(creep: Creep) {

        // 获取creep名字后缀数字编号
        const creepIndex = parseInt(creep.name.split('_')[1])

        const spawnRoomIndex = RoleReserver.spawnRoomNames.indexOf(creep.memory.spawnRoom)
        const roomNames = RoleReserver.workRoomNames[spawnRoomIndex]
        const reserverIndexs = RoleReserver.roomReserverIndexs[spawnRoomIndex]

        let roomName
        for (const index in reserverIndexs) {
            const indexs = reserverIndexs[index]

            for (const i in indexs) {
                if (indexs[i] == creepIndex) {
                    roomName = roomNames[index]
                    break
                }
            }
        }
        // console.log('spawnRoomIndex creepIndex roomName', spawnRoomIndex, creepIndex, roomName)

        // Game.spawns['Spawn1'].spawnCreep([MOVE, CLAIM], 'C01', {memory: {role: 'claimer'}});
        // Game.spawns['Spawn1'].spawnCreep([WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE], 'RR01', {memory: {role: 'claimer'}});

        const memoryData: RoleDatas[CreepRole.Reserver] = creep.memory.data as RoleDatas[CreepRole.Reserver]

        if (!memoryData) {
            creep.log('memory error')
            return
        }

        if (!memoryData.targetRoomName || memoryData.targetRoomName != roomName) {
            memoryData.targetRoomName = roomName
        }

        const room = Game.rooms[memoryData.targetRoomName]
        if (!room || room.name != creep.room.name) {
            creep.goTo(new RoomPosition(25, 25, memoryData.targetRoomName))
            return
        }

        if (!creep.room.memory.reserverCreepId) {
            creep.room.memory.reserverCreepId = creep.id
        }
        else {
            // if (!creep.room.memory.reserverCreepSpawning && creep.ticksToLive < 50) {
            //     const spawn = Game.rooms['E35S49'][STRUCTURE_SPAWN]
            //     CreepNumberSettings.doSpawnCreep(spawn, CreepRole.Reserver, data)
            //     if(status) {
            //         creep.room.memory.reserverCreepSpawning = true
            //     }
            //     else if (status == OK) {
            //         delete creep.room.memory.reserverCreepSpawning
            //     }
            // }
        }
        const status = creep.reserveController(room.controller)
        if (status == ERR_NOT_IN_RANGE) {
            creep.goTo(room.controller.pos)
        }
        else if (status == OK) {
            creep.memory.stand = true
        }
    }
}

export default RoleReserver
